package com.huaao.micropolice.root.controllers.content;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huaao.micropolice.core.common.Context;
import com.huaao.micropolice.core.model.content.Subject;
import com.huaao.micropolice.core.model.system.Dept;
import com.huaao.micropolice.core.service.content.SubjectService;
import com.huaao.micropolice.core.service.system.DeptService;
import com.huaao.micropolice.root.controllers.BaseController;

@Controller
@RequestMapping("subject")
public class SubjectController extends BaseController{

	@Autowired
	private SubjectService subjectService;
	
	@Autowired
	private DeptService deptService;
	
	@RequestMapping("index")
	public String index(){
		
		return "subject/subjectIndex";
	}
	
	
	@RequestMapping("form")
	public String form(String subjectId,HttpServletRequest reqeuest){
		Subject subject = new Subject();
		
		if (StringUtils.isNotBlank(subjectId)){
			//修改
			subject =  subjectService.get(subjectId);
		}else{
			//添加
			String parentId = reqeuest.getParameter("parent.id");
			if(StringUtils.isNotBlank(parentId)){
				subject.setParent(subjectService.get(parentId));
			}
		}
		
		/*if (subject.getParent()==null||subject.getParent().getId()==null){
			subject.setParent(new Subject());
		}
		if (subject.getDept()==null||subject.getDept().getId()==null){
			subject.setDept(new Dept());
		}
		
		request.setAttribute("dept", subject.getDept()); */
		request.setAttribute("subject", subject); 
		return "subject/subjectForm";
	}
	/**
	 * @return 栏目分页列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("listSubject")
	@ResponseBody
	public ResponseEntity<List<Map<String, Object>>> listSubject(){
		List<Subject> subjectList = subjectService.listSubject(getPage());
		
		ArrayList<Subject> destList = new ArrayList<>();
		Subject.sortList(destList, subjectList, "0");
		
//		ListOrderedMap orderedMap = getTreeHierarchy(subjectList);
//		List<Subject> destList = (List<Subject>)orderedMap.valueList();
		List<Map<String, Object>> respList = new ArrayList<>();
		for (Subject subject : destList) {
			Map<String, Object> map = new HashMap<>();
			map.put("id", subject.getId());
			map.put("name", subject.getName());
			map.put("parent_id", subject.getParent()==null||subject.getParent().getId().equals("0")?null:subject.getParent().getId());
			map.put("code", subject.getCode());
			map.put("dept_name", subject.getDept()==null?null:subject.getDept().getName());
			map.put("code", subject.getCode());
			map.put("image", subject.getImage());
			map.put("is_comment", subject.getIs_comment());
			map.put("is_audit", subject.getIs_audit());
			map.put("sort", subject.getSort());
			map.put("status", subject.getStatus());
			map.put("is_leaf", false);
			map.put("level", subject.getParent_ids()==null?0:subject.getParent_ids().split(",", -1).length);
			map.put("create_time", subject.getCreateTime());
			map.put("expanded", true);
			map.put("loaded", true);
			respList.add(map);
		}
		
		Map<String, Object> body = successMap();
		body.put("data", respList);
		return ajaxModel(MediaType.APPLICATION_JSON, respList);
	}
	
	
	private ListOrderedMap getTreeHierarchy(List<Subject> subjectList) {
		// TODO Auto-generated method stub
		ListOrderedMap orderedMap = new ListOrderedMap();
		for (Subject subject : subjectList) {
			buildMap(orderedMap, subject);
		}
		
		return orderedMap;
		
	}


	private void buildMap(ListOrderedMap orderedMap, Subject subject) {
		String id =  subject.getId();
		Subject parent = subject.getParent();
		String parentId = null;
		if(parent!=null)parentId = parent.getId();
		Object v = orderedMap.get(id);
		if(v==null){
			if(parentId==null){
				orderedMap.put(id, subject);
			}else{
				Object pv = orderedMap.get(parentId);
				if(pv==null){
					buildMap(orderedMap, parent);
				}else{
					int parentIndex = orderedMap.indexOf(parentId);
					orderedMap.put(parentIndex+1, id, subject);
				}
			}
			
		}
	}
	
	


	@RequestMapping("subjectTreeData")
	@ResponseBody
	public ResponseEntity<ArrayList<Map<String, Object>>> subjectTreeData(){
		List<Subject> subjectList = subjectService.listSubject(getPage());
		ArrayList<Map<String, Object>> respList = new ArrayList<>();
		for (Subject subject : subjectList) {
			Map<String, Object> map = new HashMap<>();
			map.put("id", subject.getId());
			map.put("name", subject.getName());
			map.put("parent_id", subject.getParent()==null?null:subject.getParent().getId());
			respList.add(map);
		}
		
		Map<String, Object> body = successMap();
		body.put("data", respList);
		return ajaxModel(MediaType.APPLICATION_JSON, respList);
	}
	@RequestMapping("deptTreeData")
	@ResponseBody
	public ResponseEntity<ArrayList<Map<String, Object>>> deptTreeData(){
		List<Dept> deptList = deptService.findAll();
		ArrayList<Map<String, Object>> respList = new ArrayList<>();
		for (Dept subject : deptList) {
			Map<String, Object> map = new HashMap<>();
			map.put("id", subject.getId());
			map.put("name", subject.getName());
			map.put("parent_id", subject.getParent()==null?null:subject.getParent().getId());
			respList.add(map);
		}
		
		Map<String, Object> body = successMap();
		body.put("data", respList);
		return ajaxModel(MediaType.APPLICATION_JSON, respList);
	}
	
	
	/**
	 * @param parentId 父栏目id
	 * @param subject 新添加栏目
	 * @return
	 */
	@RequestMapping("saveSubject")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> saveSubject(Subject subject){
		Map<String, Object> body = null;
		if(subject.getParent()!=null&&StringUtils.isNotBlank(subject.getParent().getId())){
			Subject parentSubject = subjectService.get(subject.getParent().getId());
			String parentIds = parentSubject.getParent_ids();
			subject.setParent_ids(parentIds!=null?","+parentSubject.getId():parentSubject.getId());
		}
		if(StringUtils.isBlank(subject.getId())){
			//添加
			subject.setId(null);
			subject.setCreateTime(new Date());
			subject.setCreator(Context.getCurrentUser());
			subject.setLastUpdateTime(new Date());
			subject.setUpdater(Context.getCurrentUser());
			if(subjectService.existSubjectBy(subject.getName())){
				body = failMap();
				body.put(MESSAGE, "该栏目已存在");
				return ajaxModel(MediaType.APPLICATION_JSON, body);
			}
			
			String id = subjectService.addSubject(subject);
		}else{
			//修改
			Subject oldSubject = subjectService.get(subject.getId());
			subject.setUpdater(Context.getCurrentUser());
			subject.setLastUpdateTime(new Date());
			subject.setCreateTime(oldSubject.getCreateTime());
			subject.setCreator(oldSubject.getCreator());
			subject.setParent_ids(oldSubject.getParent_ids());
			
			subjectService.updateSubject(subject);
		}
		
		subject = subjectService.get(subject.getId());
		
		Map<String, Object> map = new HashMap<>();
		map.put("id", subject.getId());
		map.put("name", subject.getName());
		map.put("parent_id", subject.getParent()==null||subject.getParent().getId().equals("0")?null:subject.getParent().getId());
		map.put("code", subject.getCode());
		map.put("dept_name", subject.getDept()==null?null:subject.getDept().getName());
		map.put("code", subject.getCode());
		map.put("image", subject.getImage());
		map.put("is_comment", subject.getIs_comment());
		map.put("is_audit", subject.getIs_audit());
		map.put("sort", subject.getSort());
		map.put("status", subject.getStatus());
		map.put("is_leaf", false);
		map.put("level", subject.getParent_ids()==null?0:subject.getParent_ids().split(",", -1).length);
		map.put("create_time", subject.getCreateTime());
		map.put("expanded", true);
		map.put("loaded", true);
		
		body = successMap();
		body.put("data", map);
		return ajaxModel(MediaType.APPLICATION_JSON, body);
	}
	
	
	@RequestMapping("deleteSubject")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> deleteSubject(String subjectId){
		Assert.hasText(subjectId, "栏目ID不能为空");
		subjectService.deleteSubject(subjectId);
		
		return ajaxModel(MediaType.APPLICATION_JSON, successMap());
	}
	
	
}
